<script setup>
import { merge, omit } from 'lodash-es';
import dayjs from 'dayjs';
import { useWatch } from '@/hooks/useWatch';
import { usePickerOption } from '@/views/hooks';
import { basicLineXAxis, basicLineYAxis, basicLineLegend } from '@/components/chart/options/baseOptions.js';
import CECharts from '@/components/chart/CECharts.vue';

const props = defineProps({
  hideDateType: { type: Boolean, default: false },
  loading: { type: Boolean, default: false },
  type: { type: String, default: 'line' },
  chartOptions: {
    type: Object,
    default: () => ({
      color: ['#26d5d5', '#d5d526', '#5afe5d'],
      series: [],
      yAxis: [{ name: '', nameTextStyle: { fontSize: 12 } }],
      grid: { bottom: 0, top: 50, left: 10, right: 10 },
      dataZoom: null,
    }),
  },
  extraOpts: { type: Object, default: () => ({}) },
  formStyle: { type: String, default: 'u-df-spb' },
  mergeDefault: { type: Boolean, default: true }
});
const emit = defineEmits(['handleDateParams']);
const rangeType = ref({
  d: {
    type: 'daterange',
    fmt: 'yyyy-MM-dd',
    default: [dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().subtract(1, 'day').format('YYYY-MM-DD')],
    pickerOptions: usePickerOption('d'),
  },
  m: {
    type: 'monthrange',
    fmt: 'yyyy-MM',
    default: [dayjs().subtract(5, 'month').format('YYYY-MM'), dayjs().format('YYYY-MM')],
    pickerOptions: usePickerOption('m'),
  },
  y: { type: 'yearrange', fmt: 'yyyy', default: [dayjs().subtract(2, 'year').format('YYYY'), dayjs().format('YYYY')] },
});
const dateRange = ref(rangeType.value.d.default);
const yearRange = ref({ sYear: null, eYear: null });
// 开始时间不能大于结束时间
const pickerOptsStart = ref({
  disabledDate: time => {
    if (yearRange.value.eYear) {
      return (
        dayjs(time) > dayjs(yearRange.value.eYear) || dayjs(time) < dayjs(yearRange.value.eYear).subtract(2, 'year')
      );
    }
  },
});
// 结束时间不能小于开始时间
const pickerOpts = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRange.value.sYear) || dayjs(time) > dayjs(yearRange.value.sYear).add(2, 'year');
  },
});
const dateParams = ref({
  dateType: 'd',
  startTime: dateRange.value[0],
  endTime: dateRange.value[1],
});
const chartOpts = ref(props.chartOptions);

const dateChange = val => {
  dateParams.value.startTime = val[0];
  dateParams.value.endTime = val[1];
};
const yearChange = () => {
  dateParams.value.startTime = yearRange.value.sYear;
  dateParams.value.endTime = yearRange.value.eYear;
};
useWatch(
  () => dateParams.value.dateType,
  (n, o) => {
    if (n !== o) {
      if (n !== 'y') {
        dateRange.value = rangeType.value[n].default;
        dateParams.value.startTime = dateRange.value[0];
        dateParams.value.endTime = dateRange.value[1];
      } else {
        yearRange.value.sYear = rangeType.value.y.default[0];
        yearRange.value.eYear = rangeType.value.y.default[1];
        dateParams.value.startTime = yearRange.value.sYear;
        dateParams.value.endTime = yearRange.value.eYear;
      }
    }
  },
);
useWatch(dateParams, n => emit('handleDateParams', props.hideDateType ? omit(n, ['dateType']) : n), { deep: true });
useWatch(
  () => props.extraOpts,
  n => {
    props.type === 'line' && chartOpts.value?.dataset?.source && (chartOpts.value.dataset.source = []);
    props.type === 'pie' && chartOpts.value?.series?.length && (chartOpts.value.series = []);
    chartOpts.value = merge({}, props.mergeDefault ? chartOpts.value : {}, n);
  },
  { deep: true },
);
defineExpose({ chartOpts, dateParams });
</script>

<template>
  <div>
    <el-form :model="dateParams" :class="formStyle">
      <el-form-item>
        <el-form-item v-if="rangeType[dateParams.dateType].type !== 'yearrange'">
          <el-date-picker v-model="dateRange" :type="rangeType[dateParams.dateType].type ?? 'daterange'"
            :key="rangeType[dateParams.dateType].type ?? 'daterange'"
            :value-format="rangeType[dateParams.dateType].fmt ?? 'yyyy-MM-dd'"
            :picker-options="rangeType[dateParams.dateType].pickerOptions" :clearable="false" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" size="mini" align="left"
            style="width: 240px; margin-right: 20px" @change="dateChange" />
        </el-form-item>
        <el-form-item v-else>
          <el-date-picker v-model="yearRange.sYear" :picker-options="pickerOptsStart" :clearable="false" type="year"
            value-format="yyyy" placeholder="开始年份" size="mini" style="width: 115px" class="u-mr5"
            @change="yearChange" />
          <el-date-picker v-model="yearRange.eYear" :picker-options="pickerOpts" :clearable="false" type="year"
            value-format="yyyy" placeholder="结束年份" size="mini" style="width: 115px" @change="yearChange" />
        </el-form-item>
      </el-form-item>
      <el-form-item v-show="!hideDateType" prop="dateType" class="u-df-ct">
        <el-radio-group v-model="dateParams.dateType" size="mini">
          <el-radio-button label="d">日</el-radio-button>
          <el-radio-button label="m">月</el-radio-button>
          <el-radio-button label="y">年</el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <CECharts v-loading="loading" :type="type" :options="chartOpts" style="height: calc(100% - 28px)" />
  </div>
</template>

<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 0;
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .el-form-item__content {
    display: flex;
    justify-content: center;
    align-items: center;
    line-height: 28px;
  }
}

::v-deep .el-radio-button--mini .el-radio-button__inner {
  padding: 6px 8px;
  height: 28px !important;
  margin-right: 3px;
  border-radius: 0;
}
</style>
